package com.ligq.vbasedemo.view

import android.content.Context
import android.hardware.Camera
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.ligq.vbasedemo.MainActivity.TAG
import com.ligq.vbasedemo.encode.H264CameraEncode
import java.lang.Exception

class LocalSurfaceView(
    context: Context?,
    attrs: AttributeSet?,
    defStyleAttr: Int,
    defStyleRes: Int
) : SurfaceView(context, attrs, defStyleAttr, defStyleRes), Camera.PreviewCallback,
    SurfaceHolder.Callback {
    private lateinit var mCamera: Camera
    private lateinit var size: Camera.Size
    private lateinit var buff: ByteArray
    private lateinit var h264Encoder: H264CameraEncode

    constructor(context: Context?) : this(context, null)

    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : this(
        context,
        attrs,
        defStyle,
        0
    )

    init {
        holder?.addCallback(this)
    }

    private fun startPreview() {
        mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
        val parameters = mCamera.parameters
        size = parameters.previewSize
        try {
            mCamera.setPreviewDisplay(holder)
            mCamera.setDisplayOrientation(90)
            //NV21数据大小为像素总和的1.5倍
            buff = ByteArray(size.width * size.height * 3 / 2)
            mCamera.addCallbackBuffer(buff)
            //添加预览监听，主要用来编码逐帧数据
            mCamera.setPreviewCallbackWithBuffer(this)
            mCamera.startPreview()
        } catch (e: Exception) {
            Log.e(TAG, "startPreview: ", e)
        }
    }

    //yuv 数据，NV21，需要转换为NV12
    override fun onPreviewFrame(data: ByteArray?, camera: Camera?) {
        if (!this::h264Encoder.isInitialized) {
            h264Encoder = H264CameraEncode(size.width, size.height)
            h264Encoder.startLive()
        }
        h264Encoder.encodeFrame(data)
        mCamera.addCallbackBuffer(data)
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        startPreview()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {

    }
}